package com.holyn.guofang.view.distinguish;

import android.app.Activity;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.holyn.guofang.R;
import com.holyn.guofang.model.webhttp.HttpConfigure;
import com.holyn.guofang.model.webhttp.wo.ImagePartitionWo;
import com.holyn.guofang.model.webhttp.wo.ImageSimilarWo;
import com.holyn.guofang.model.webhttp.wo.ImageWo;
import com.holyn.guofang.presenter.BaseView;
import com.holyn.guofang.presenter.brand.BrandContract;
import com.holyn.guofang.presenter.brand.BrandPresenter;
import com.holyn.guofang.presenter.distinguish.DistinguishContract;
import com.holyn.guofang.presenter.distinguish.DistinguishPresenter;
import com.holyn.guofang.view.BaseActivity;
import com.holyn.guofang.viewcommon.popupwindow.PopupSingleSelectFromBottom;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Holyn on 2017/7/25.
 * 追加替换
 */

public class ImgSimilarActivity extends BaseActivity implements BaseView,
        BrandContract.ImgPartitionView, DistinguishContract.UploadView, BrandContract.SimilarImgView {

    private static final int REQUEST_ACTION_UPLOAD_IMAGE = 0x0001;
    private static final int REQUEST_ACTION_POST_IMG_PARTITION = 0x0002;
    private static final int REQUEST_ACTION_POST_IMG_SIMILAR = 0x0003;

    private static final int REQUEST_CODE_GO_REPLACE = 0x0001;

    @BindView(R.id.rv_partition)
    RecyclerView rvPartition;
    @BindView(R.id.ll_similar_num)
    LinearLayout llSimilarNum;
    @BindView(R.id.rv_similar)
    RecyclerView rvSimilar;
    @BindView(R.id.btn_add_son)
    Button btnAddSon;
    @BindView(R.id.btn_replace_main)
    Button btnReplaceMain;
    @BindView(R.id.tv_similar_num)
    TextView tvSimilarNum;

    private String imagePath;
    private String SrcImgID;
    private String ImgIDs;
    private Integer TopCount = 12;
    private String mainImageUrl = "";
    private ArrayList<String> sonImageUrlList;
    private ArrayList<String> mainAndSonImageUrlList = new ArrayList<>();
    private ArrayList<String> similarImageUrlList = new ArrayList<>();

    private DistinguishContract.Presenter disPresenter;
    private BrandContract.Presenter brandPresenter;

    private ImgPartitionRecyclerAdapter imgPartitionRecyclerAdapter;
    private ImgSimilarRecyclerAdapter imgSimilarRecyclerAdapter;


    private List<String> topCountList = new ArrayList<>();
    private PopupSingleSelectFromBottom popupSingleSelectNum;

    public static void startForResult(Activity fromActivity, String imagePath, String SrcImgID, String mainImageUrl, ArrayList<String> sonImageUrlList, int requestCode) {
        Intent intent = new Intent(fromActivity, ImgSimilarActivity.class);
        intent.putExtra(SeniorDistinguishActivity.INTENT_KEY_IMAGE_PATH, imagePath);
        intent.putExtra(SeniorDistinguishActivity.INTENT_KEY_SRC_IMG_ID, SrcImgID);
        intent.putExtra(SeniorDistinguishActivity.INTENT_KEY_MAIN_IMG_URL, mainImageUrl);
        intent.putStringArrayListExtra(SeniorDistinguishActivity.INTENT_KEY_SON_IMG_URL_LIST, sonImageUrlList);
        fromActivity.startActivityForResult(intent, requestCode);
    }

    @Override
    protected int getLayoutResID() {
        return R.layout.activity_img_similar;
    }

    @Override
    protected void onMyCreate() {
        ButterKnife.bind(this);
        showToolbar("追加或替换近似图样");
        initData();
        initPopupSingleSelectNumView();
    }

    private void initData() {
        imagePath = getIntent().getStringExtra(SeniorDistinguishActivity.INTENT_KEY_IMAGE_PATH);
        SrcImgID = getIntent().getStringExtra(SeniorDistinguishActivity.INTENT_KEY_SRC_IMG_ID);
        mainImageUrl = getIntent().getStringExtra(SeniorDistinguishActivity.INTENT_KEY_MAIN_IMG_URL);
        sonImageUrlList = getIntent().getStringArrayListExtra(SeniorDistinguishActivity.INTENT_KEY_SON_IMG_URL_LIST);

        topCountList.add("12");
        topCountList.add("22");
        topCountList.add("32");
        topCountList.add("42");
        topCountList.add("52");
        topCountList.add("62");

        disPresenter = new DistinguishPresenter(this);
        disPresenter.addUploadViewListener(this);
        brandPresenter = new BrandPresenter(this);
        brandPresenter.addImgPartitionView(this);
        brandPresenter.addSimilarImgView(this);

        if (TextUtils.isEmpty(SrcImgID)) {
            disPresenter.uploadImage(REQUEST_ACTION_UPLOAD_IMAGE, imagePath);
        } else if (sonImageUrlList.size() == 0){
            brandPresenter.postImgPartition(REQUEST_ACTION_POST_IMG_PARTITION, SrcImgID);
        } else {
            initImgPartitionRecyclerView(null);
            postSimilarImg();
        }
    }

    private void postSimilarImg(){
        ImgIDs = mainImageUrl.substring(mainImageUrl.lastIndexOf("/")+1);
        for (String sonImageUrl: sonImageUrlList){
            ImgIDs = ImgIDs + ";" + sonImageUrl.substring(sonImageUrl.lastIndexOf("/")+1);
        }

        brandPresenter.postSimilarImg(REQUEST_ACTION_POST_IMG_SIMILAR, SrcImgID, ImgIDs, TopCount);
    }

    private void initImgPartitionRecyclerView(ArrayList<String> defaultSonImgLIst){
        mainAndSonImageUrlList.clear();
        mainAndSonImageUrlList.add(mainImageUrl);
        if (defaultSonImgLIst != null){
            mainAndSonImageUrlList.addAll(defaultSonImgLIst);
        } else {
            mainAndSonImageUrlList.addAll(sonImageUrlList);
        }
        imgPartitionRecyclerAdapter = new ImgPartitionRecyclerAdapter(mainAndSonImageUrlList);
        LinearLayoutManager layoutManager = new LinearLayoutManager(ImgSimilarActivity.this);
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        rvPartition.setLayoutManager(layoutManager);
        rvPartition.setAdapter(imgPartitionRecyclerAdapter);
    }

    private void initImgSimilarRecyclerView(){
        imgSimilarRecyclerAdapter = new ImgSimilarRecyclerAdapter(similarImageUrlList);
        imgSimilarRecyclerAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                imgSimilarRecyclerAdapter.toggleCheckStatus(i);
            }
        });
        LinearLayoutManager layoutManager = new LinearLayoutManager(ImgSimilarActivity.this);
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        rvSimilar.setLayoutManager(layoutManager);
        rvSimilar.setAdapter(imgSimilarRecyclerAdapter);
    }

    private void initPopupSingleSelectNumView(){
        popupSingleSelectNum = new PopupSingleSelectFromBottom(ImgSimilarActivity.this, "选择请求的个数", topCountList);
        popupSingleSelectNum.setOnItemClickListener(new PopupSingleSelectFromBottom.OnItemClickListener() {
            @Override
            public void onItemClick(String item, int position) {
                tvSimilarNum.setText(topCountList.get(position));
                TopCount = Integer.parseInt(topCountList.get(position));
                postSimilarImg();
            }
        });
    }

    @OnClick({R.id.ll_similar_num, R.id.btn_add_son, R.id.btn_replace_main})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_similar_num:
                popupSingleSelectNum.showPopupWindow();
                break;
            case R.id.btn_add_son:
                if (imgSimilarRecyclerAdapter.getCheckData().size() == 0){
                    toastMsg("请选择近似图");
                } else {
                    sonImageUrlList.addAll(imgSimilarRecyclerAdapter.getCheckData());
                    Intent intent = getIntent();
                    intent.putExtra(SeniorDistinguishActivity.INTENT_KEY_SRC_IMG_ID, SrcImgID);
                    intent.putExtra(SeniorDistinguishActivity.INTENT_KEY_MAIN_IMG_URL, mainImageUrl);
                    intent.putStringArrayListExtra(SeniorDistinguishActivity.INTENT_KEY_SON_IMG_URL_LIST, sonImageUrlList);
                    setResult(Activity.RESULT_OK, intent);
                    ImgSimilarActivity.this.finish();
                }
                break;
            case R.id.btn_replace_main:
                String sonUrl = imgSimilarRecyclerAdapter.getOneCheckSonUrl();
                if (TextUtils.isEmpty(sonUrl)){
                    toastMsg("请选择一个近似图");
                } else if (sonUrl.equals("error")){
                    toastMsg("注意：只能选择一个近似图");
                } else {
                    ImgSimilarReplaceActivity.startForResult(ImgSimilarActivity.this, sonUrl, REQUEST_CODE_GO_REPLACE);
                }
                break;
        }
    }

    @Override
    public void requestStart(Integer requestAction) {
        showLoadingDialog();
    }

    @Override
    public void requestError(Integer requestAction, Throwable e) {
        toastMsg("出现异常");
        closeLoadingDialog();
    }

    @Override
    public void requestComplete(Integer requestAction) {

    }

    @Override
    public void responseSuccess(int requestAction, ImagePartitionWo imagePartitionWo) {
        if (imagePartitionWo.getStatus() == HttpConfigure.STATUS_SUCCESS){
            ArrayList<String> defaultSonImgLIst = new ArrayList<>();
            List<ImagePartitionWo.DataBean.DefimageBean> defimageBeanList = imagePartitionWo.getData().getDefimage();
            for (ImagePartitionWo.DataBean.DefimageBean defimageBean: defimageBeanList){
                defaultSonImgLIst.add(defimageBean.getDefImageUrl());
            }
            sonImageUrlList.clear();
//            sonImageUrlList.addAll(defaultSonImgLIst);
            initImgPartitionRecyclerView(defaultSonImgLIst);//显示主图、子图RecyclerView
            postSimilarImg();
        } else {
            closeLoadingDialog();
        }
    }

    @Override
    public void responseSuccess(int requestAction, ImageSimilarWo imageSimilarWo) {
        if (imageSimilarWo.getStatus() == HttpConfigure.STATUS_SUCCESS){
            List<ImageSimilarWo.DataBean.UrlBean> urlBeanList = imageSimilarWo.getData().getUrl();
            similarImageUrlList.clear();
            for (ImageSimilarWo.DataBean.UrlBean urlBean: urlBeanList){
                similarImageUrlList.add(urlBean.getImgUrl());
            }

            //显示近似图RecyclerView
            initImgSimilarRecyclerView();
        }
        closeLoadingDialog();
    }

    @Override
    public void responseSuccess(Integer requestAction, ImageWo imageWo) {
        if (imageWo.getStatus() == HttpConfigure.STATUS_SUCCESS){
            SrcImgID = imageWo.getSrcImgID();
            mainImageUrl = imageWo.getUrl();
            brandPresenter.postImgPartition(REQUEST_ACTION_POST_IMG_PARTITION, SrcImgID);
        } else {
            closeLoadingDialog();
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK){
            switch (requestCode){
                case REQUEST_CODE_GO_REPLACE:
                    mainImageUrl = data.getStringExtra(ImgSimilarReplaceActivity.INTENT_KEY_READY_REPLACE_SON_IMG_URL);
                    Intent intent = getIntent();
                    intent.putExtra(SeniorDistinguishActivity.INTENT_KEY_SRC_IMG_ID, SrcImgID);
                    intent.putExtra(SeniorDistinguishActivity.INTENT_KEY_MAIN_IMG_URL, mainImageUrl);
                    intent.putStringArrayListExtra(SeniorDistinguishActivity.INTENT_KEY_SON_IMG_URL_LIST, sonImageUrlList);
                    setResult(Activity.RESULT_OK, intent);
                    ImgSimilarActivity.this.finish();
                    break;
            }
        }
    }

    private class ImgPartitionRecyclerAdapter extends BaseQuickAdapter<String, BaseViewHolder>{
        public ImgPartitionRecyclerAdapter(@Nullable List<String> data) {
            super(R.layout.item_similar_img_partition, data);
        }

        @Override
        protected void convert(BaseViewHolder baseViewHolder, String s) {
            int position = baseViewHolder.getAdapterPosition();
            TextView tvTitle = baseViewHolder.getView(R.id.tv_title);
            ImageView ivSon = baseViewHolder.getView(R.id.iv_son);
            if (position == 0){
                tvTitle.setText("主图：");
            } else if (position == 1) {
                tvTitle.setText("分拆子图：");
            } else {
                tvTitle.setText("");
            }
            Glide.with(ImgSimilarActivity.this).load(s)
//                    .error(R.drawable.ic_empty_image)
                    .into(ivSon);
        }
    }

    private class ImgSimilarRecyclerAdapter extends BaseQuickAdapter<String, BaseViewHolder>{
        private List<Boolean> isCheckList = new ArrayList<>();

        public ImgSimilarRecyclerAdapter(@Nullable List<String> data) {
            super(R.layout.item_similar_img, data);
            for (int i = 0; i<data.size(); i++){
                isCheckList.add(false);
            }
        }

        @Override
        protected void convert(BaseViewHolder baseViewHolder, String s) {
            ImageView ivSon = baseViewHolder.getView(R.id.iv_son);
            Glide.with(ImgSimilarActivity.this).load(s)
//                    .error(R.drawable.ic_empty_image)
                    .into(ivSon);

            CheckBox cbSelect = baseViewHolder.getView(R.id.cb_select);
            cbSelect.setChecked(isCheckList.get(baseViewHolder.getAdapterPosition()));
        }

        public void toggleCheckStatus(int postition){
            isCheckList.set(postition, !isCheckList.get(postition));
            notifyDataSetChanged();
        }

        public String getOneCheckSonUrl(){
            String result = "";
            int checkCount = 0;
            for (int i = 0; i<isCheckList.size(); i++){
                boolean isCheck = isCheckList.get(i);
                if (isCheck){
                    checkCount ++;
                    if (checkCount >1){
                        return "error";
                    }
                    result = getData().get(i);
                }
            }
            return result;
        }

        public void reSetCheck(){
            for (boolean isCheck: isCheckList){
                isCheck = false;
            }
            notifyDataSetChanged();
        }

        public ArrayList<String> getCheckData(){
            ArrayList<String> selectUrlList = new ArrayList<>();
            Iterator<String> iteratorStr = getData().iterator();
            int i = 0;
            while (iteratorStr.hasNext()){
                String s = iteratorStr.next();
                if (isCheckList.get(i)){
                    selectUrlList.add(s);
//                    iteratorStr.remove();
                }
                i++;
            }

//            Iterator<Boolean> iteratorCheck = isCheckList.iterator();
//            while (iteratorCheck.hasNext()){
//                boolean isCheck = iteratorCheck.next();
//                if (isCheck){
//                    iteratorCheck.remove();
//                }
//            }

            return selectUrlList;
        }
    }
}
